package com.mytijian.task.zookeeper.listener.manager;

import com.mytijian.task.zookeeper.LeaderService;
import com.mytijian.task.httprequest.HttpRequest;
import com.mytijian.task.task.handout.HandoutController;
import com.mytijian.task.util.IpAddressUtil;
import com.mytijian.task.zookeeper.ZookeeperRegistryCenter;
import com.mytijian.task.zookeeper.listener.AbstractDataChangeListener;
import com.mytijian.task.zookeeper.path.NodePath;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

public class NodeListenerManager extends AbstractListenerManager {
    private Logger logger = LoggerFactory.getLogger(NodeListenerManager.class);
    private String serverPath;
    private HandoutController handoutController;
    public NodeListenerManager(ZookeeperRegistryCenter zookeeperRegistryCenter,
                               LeaderService leaderService,
                               HandoutController handoutController,
                               String serverPath) {
        super(zookeeperRegistryCenter, leaderService);
        this.handoutController = handoutController;
        this.serverPath = serverPath;
    }
    @Override
    public void start() {
        addListener(NodePath.node, new WatchNodeIpRemoveListener());
    }

    class WatchNodeIpRemoveListener extends AbstractDataChangeListener {
        @Override
        protected void dataChanged(String path, TreeCacheEvent.Type eventType, String data) {
            // 只有主server节点才能分配任务
            if (eventType != TreeCacheEvent.Type.NODE_REMOVED) {
                return;
            }
            String[] nodes = path.split("/");
            if (nodes.length <=0 ) {
                return;
            }
            String ipAndPort = nodes[nodes.length - 1];
            String ip = ipAndPort.split(":")[0];
            // 删除节点是否是本机
            if (IpAddressUtil.getLocalHost().equals(ip)) {
                logger.error("节点 ip = {},断开重新注入",ip,path);
                try {
                    zookeeperRegistryCenter.persistEphemeral(path, data);

                }catch (Exception e) {
                    logger.error("重新注入节点失败，当前节点将会退出jvm e= {}", e);
                    System.exit(0);
                }
                return;
            } else {
                // 其他节点等待断开节点2s中，2s之内断开节点是否会重新注入 ip到node下。
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String value = zookeeperRegistryCenter.get(path);
            if (value != null) {
                return;
            }
            if (!leaderService.isLeaderUntilBlock()) {
                return;
            }
            try {
                ResponseEntity response = new HttpRequest(serverPath, 2 * 1000, 2 * 1000).getForRequest(ipAndPort, "/workNode/" + "isOk", null);
                // 该节点与zookeeper出现分区
                if (response.getStatusCodeValue() == 200) {
                    return;
                }
            }catch (Exception e) {
                logger.error("请求 ip = {}节点失败 e = {}", data, e);
            }


//            String failoverIpPath = taskNode.getFullNodePath(FailOverPath.failOverIp(ip));
//            List<String> taskIdentifys = zookeeperRegistryCenter.getChildrenKeys(failoverIpPath);
//            if (CollectionUtils.isEmpty(taskIdentifys)) {
//                return;
//            }
//            List<TaskIdentify> taskIdentifies = new ArrayList<>(taskIdentifys.size());
//            for (String taskIdentifyString : taskIdentifys) {
//                String processingSubTaskId = zookeeperRegistryCenter.get(failoverIpPath + "/" + taskIdentifyString);
//                TaskIdentify taskIdentify = TaskIdentify.build(taskIdentifyString);
//
//                if (!StringUtils.isEmpty(processingSubTaskId)) {
//                    taskIdentify.setProcessingSubTaskId(Integer.parseInt(processingSubTaskId));
//                }
//                if (Objects.equals(true, taskIdentify.getNeedFailOver())) {
//
//                    taskIdentifies.add(taskIdentify);
//                }
//            }
            handoutController.handoutWithMutiNode(ip);
        }
    }
//    class WatchNodeIpAddListener extends AbstractDataChangeListener {
//
//        @Override
//        protected void dataChanged(String path, TreeCacheEvent.Type eventType, String data) {
//            if (eventType != TreeCacheEvent.Type.NODE_ADDED) {
//                return;
//            }
//            if (!Objects.equals(path, taskNode.getFullNodePath(NodePath.getNodeLocalIpAndPort(nodePort)))) {
//                return;
//            }
//            String failoverIpPath = taskNode.getFullNodePath(FailOverPath.failoverLocalIp);
//            List<String> taskIdentifys = zookeeperRegistryCenter.getChildrenKeys(failoverIpPath);
//            if (CollectionUtils.isEmpty(taskIdentifys)) {
//                return;
//            }
//
//            HandoutController handoutController = new HandoutController(zookeeperRegistryCenter, taskNode, taskIdentifyOperateService, leaderService);
//            handoutController.handoutCurrentNode(taskIdentifies);
//
//        }
//    }
}
